#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <signal.h>

#define SERVER_IP "127.0.0.1"
#define PORT 12345
#define BUFFER_SIZE 1024


int main(int argc, char *argv[]) {
    int client_socket;
    struct sockaddr_in server_addr;
    char message[BUFFER_SIZE];
    char recv_buf[BUFFER_SIZE];

    // 创建客户端套接字
    if ((client_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("Error creating socket");
        exit(1);
    }

    // 设置服务器地址
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);

    inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr);

    // 连接到服务器
    if (connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        perror("Error connecting to server");
        exit(1);
    }


    // 创建子进程
    int pid;
    pid = fork();
    if (pid == -1) {
        return 1;
    }
    if (pid == 0) {
        while(1)
        {
            ssize_t bytes_received = recv(client_socket, recv_buf, BUFFER_SIZE, 0);

            if (bytes_received <= 0) {
                perror("close connection");
                break;
            }
            recv_buf[bytes_received] = '\0';
            printf("Received from server: %s\n", recv_buf);
        }
    } else {
        // 循环发送消息给服务器
        while (1) {
            printf("Enter a message: ");
            fgets(message, BUFFER_SIZE, stdin); // 从标准输入读取用户输入
            send(client_socket, message, strlen(message), 0);
        }
        close(client_socket);
    }

    return 0;
}